package src.main.java.org.reflect.obtainVariable;

import java.lang.reflect.Field;

/*
* 获取类的成员变量
* */
public class TestField {
    public static void main(String[] args) throws Exception {
        ///1.得到类的class对象
        Class catClass = Cat.class;

        //2.获取类的全部成员变量
        Field[] fields = catClass.getFields();//获取public的成员变量
        Field[] declaredFields = catClass.getDeclaredFields(); //获取所有成员变量
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField.getName()+"-->"+declaredField.getType());
        }

        Field name = catClass.getDeclaredField("name"); //获取某个成员变量
        System.out.println(name.getName()+"---"+name.getType());

        Field age = catClass.getDeclaredField("age");
        System.out.println(age.getName()+"---"+age.getType());

        //赋值
        Cat cat = new Cat();
        name.setAccessible(true);
        name.set(cat,"咖啡猫");
        System.out.println(cat);

        //取值
        String name1 = (String) name.get(cat);
        System.out.println(name1);

    }
}
